package com.dpad.telematicsclientapp.utils;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dpad.crmclientapp.android.R;
import com.dpad.crmclientapp.android.modules.acbd.CarCareActivity;
import com.dpad.crmclientapp.android.modules.czdh.activity.Czdh3Activity;
import com.dpad.crmclientapp.android.modules.dczz.activity.DczzActivity;
import com.dpad.crmclientapp.android.modules.dzwl.activity.DzwlActivity;
import com.dpad.crmclientapp.android.modules.internet_of_vehicles.adapter.TopPopuWindowAdapter;
import com.dpad.crmclientapp.android.modules.internet_of_vehicles.bean.HomeCarDataBean;
import com.dpad.crmclientapp.android.modules.llcx.activity.LlcxActivity2;
import com.dpad.crmclientapp.android.modules.xcjl.activity.XcjlActivity;
import com.dpad.crmclientapp.android.util.utils.Constant;
import com.dpad.crmclientapp.android.util.utils.UIUtils;
import com.dpad.telematicsclientapp.adapter.TopPopuWindowAdapter;
import com.dpad.telematicsclientapp.android.R;
import com.dpad.telematicsclientapp.netlibrary.newapp.entity.HomeCarDataBean;
import com.dpad.telematicsclientapp.util.utils.Constant;
import com.dpad.telematicsclientapp.util.utils.UIUtils;
import com.socks.library.KLog;

import java.util.List;

/**
 * ================================================
 * 作    者：booob
 * 版    本：1.0
 * 创建日期：2018-08-22-0022 14:08
 * 描    述：
 * 修订历史：
 * ================================================
 */
public class PopupMenuUtil {

    private static final String TAG = "PopupMenuUtil";

    String vin;
    View bgView;

    public static PopupMenuUtil getInstance() {
        return MenuUtilHolder.INSTANCE;
    }

    private static class MenuUtilHolder {
        public static PopupMenuUtil INSTANCE = new PopupMenuUtil();
    }

    public interface OnItemCheckedChange {
        void OnItemCheckedLister(int index);
    }

    public OnItemCheckedChange onItemCheckedChange;
    private View rootVew;
    private View topRootVew;
    private PopupWindow popupWindow;
    private PopupWindow topPopuWindow;

    private RelativeLayout rlClick, pop_window_partent;
    private ImageView ivBtn;
    private LinearLayout carWifiLl, carSaveLl, carCallLl, carRecordLl, carCollectionLl, carQueryLl;

    private RecyclerView recyclerView;
    /**
     * 动画执行的 属性值数组
     */
    float animatorProperty[] = null;
    /**
     * 第一排图 距离屏幕底部的距离
     */
    int top = 0;
    /**
     * 第二排图 距离屏幕底部的距离
     */
    int bottom = 0;

    /**
     * 创建 popupWindow 内容
     *
     * @param context context
     */
    private void _createView(final Activity context) {
        rootVew = LayoutInflater.from(context).inflate(R.layout.popup_menu, null);
        popupWindow = new PopupWindow(context);
//        popupWindow = new PopupWindow(rootVew,
//                LinearLayout.LayoutParams.MATCH_PARENT,
//                LinearLayout.LayoutParams.MATCH_PARENT);

        popupWindow.setContentView(rootVew);
        //设置为失去焦点 方便监听返回键的监听
        popupWindow.setFocusable(false);
        popupWindow.setWidth(WindowManager.LayoutParams.MATCH_PARENT);
        popupWindow.setHeight(WindowManager.LayoutParams.MATCH_PARENT);
        popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        // 如果想要popupWindow 遮挡住状态栏可以加上这句代码
        popupWindow.setClippingEnabled(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setOutsideTouchable(true);

        if (animatorProperty == null) {
            top = dip2px(context, 310);
            bottom = dip2px(context, 210);
//            animatorProperty = new float[]{bottom, 120, -60, -40 - 10, 0};
            animatorProperty = new float[]{bottom, 90, -50, -20 - 10, 0};
        }

        initLayout(context);
    }


    private void creatTopPopuWindow(final Context context,List<HomeCarDataBean.ResultBean.VehinfosBean> vehinfosBeans, OnItemCheckedChange onItemCheckedChange) {
        topRootVew = LayoutInflater.from(context).inflate(R.layout.popup_car_top, null);
        topPopuWindow = new PopupWindow(topRootVew,
                LinearLayout.LayoutParams.MATCH_PARENT,
               UIUtils.dip2px(200));
        //设置为失去焦点 方便监听返回键的监听
        topPopuWindow.setFocusable(true);

        // 如果想要popupWindow 遮挡住状态栏可以加上这句代码
        //popupWindow.setClippingEnabled(false);
//        topPopuWindow.setBackgroundDrawable(new BitmapDrawable());
        topPopuWindow.setOutsideTouchable(true);

        initTopLayout(context, vehinfosBeans, onItemCheckedChange);
    }

    /**
     * dp转化为px
     *
     * @param context  context
     * @param dipValue dp value
     * @return 转换之后的px值
     */
    public static int dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    /**
     * 初始化 view
     */
    private void initLayout(Activity context) {
        rlClick = rootVew.findViewById(R.id.pop_rl_click);
        ivBtn = rootVew.findViewById(R.id.pop_iv_img);
        carWifiLl = rootVew.findViewById(R.id.car_wifi_ll);
        carSaveLl = rootVew.findViewById(R.id.car_save_ll);
        carCallLl = rootVew.findViewById(R.id.car_call_ll);
        carRecordLl = rootVew.findViewById(R.id.car_record_ll);
        carCollectionLl = rootVew.findViewById(R.id.car_collection_ll);
        carQueryLl = rootVew.findViewById(R.id.car_query_ll);
        pop_window_partent = rootVew.findViewById(R.id.pop_window_partent);

        rlClick.setOnClickListener(new MViewClick(0, context));

        carWifiLl.setOnClickListener(new MViewClick(1, context));
        carSaveLl.setOnClickListener(new MViewClick(2, context));
        carCallLl.setOnClickListener(new MViewClick(3, context));
        carRecordLl.setOnClickListener(new MViewClick(4, context));
        carCollectionLl.setOnClickListener(new MViewClick(5, context));
        carQueryLl.setOnClickListener(new MViewClick(6, context));

        pop_window_partent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                _rlClickAction();
            }
        });

    }


    private void initTopLayout(Context context,List<HomeCarDataBean.ResultBean.VehinfosBean> carNums, OnItemCheckedChange onItemCheckedChange) {
        recyclerView = topRootVew.findViewById(R.id.pop_recyclevew);
        BaseQuickAdapter adapter = new TopPopuWindowAdapter(carNums);
        recyclerView.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false));
        adapter.bindToRecyclerView(recyclerView);
        recyclerView.setAdapter(adapter);
//        recyclerView.addItemDecoration(new RecyclerViewDivider(context, LinearLayoutManager.HORIZONTAL));
//        recyclerView.addItemDecoration(new RecyclerViewDivider(context, LinearLayoutManager.HORIZONTAL, UIUtils.dip2px(1), context.getResources().getColor(R.color.color_3B4757)));

        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                if (!carNums.get(position).isChecked()) {
                    for (HomeCarDataBean.ResultBean.VehinfosBean vehinfosBean : carNums) {
                        vehinfosBean.setChecked(false);
                    }
                    carNums.get(position).setChecked(true);
                    adapter.notifyDataSetChanged();
                    onItemCheckedChange.OnItemCheckedLister(position);
                }

                for (HomeCarDataBean.ResultBean.VehinfosBean vehinfosBean : carNums) {
                    KLog.e(vehinfosBean.isChecked() + "是否选中");
                }
                if (topPopuWindow != null) {
                    topPopuWindow.dismiss();
                    topPopuWindow = null;
                }

            }
        });
    }

    /**
     * 点击事件
     */
    private class MViewClick implements View.OnClickListener {

        public int index;
        public Activity context;

        public MViewClick(int index, Activity context) {
            this.index = index;
            this.context = context;
        }

        @Override
        public void onClick(View v) {
            if (index == 0) {
                //加号按钮点击之后的执行
                _rlClickAction();
            } else {
                switch (index) {
                    case 1://行车记录
//                        Intent intent_wifi = new Intent(context, XcjlActivity.class);
//                        context.startActivity(intent_wifi);
                        Intent intent_xcjl=new Intent(context,XcjlActivity.class);
                        intent_xcjl.putExtra("vin",vin);
                        context.startActivity(intent_xcjl);

                        break;
                    case 2://电子围栏
                        Intent intent=new Intent(context, DzwlActivity.class);
                        intent.putExtra("vin", vin);
                        context.startActivity(intent);

                        break;
                    case 3://盗车追踪
                        Intent intent1 = new Intent(context, DczzActivity.class);
                        context.startActivity(intent1);
                        break;
                    case 4://爱车保养
                        Intent intent_carCare = new Intent(context, CarCareActivity.class);
                        context.startActivity(intent_carCare);
                        break;
                    case 5://车载导航
//                        if (MainApplicaton.sIsLogin) {
//                            context.startActivity(new Intent(context, CollectionActivity.class));
//                        } else {
//                            context.startActivity(new Intent(context, LoginActivity.class));
//                        }
                        Intent intent2 = new Intent(context, Czdh3Activity.class);
                        intent2.putExtra("vin", vin);
                        context.startActivity(intent2);

                        break;
                    case 6://流量查询
                        Intent intent3 = new Intent(context, LlcxActivity2.class);
                        intent3.putExtra("vin", vin);
                        context.startActivityForResult(intent3, Constant.LLCX_REQUEST_CODE);
                        break;
                }
                _rlClickAction();
//                showToast(context, "index=" + index);
            }
        }
    }


    /**
     * 刚打开popupWindow 执行的动画
     */
    private void _openPopupWindowAction() {
        ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(ivBtn, "rotation", 0f, 180f);
        objectAnimator.setDuration(400);
        objectAnimator.start();

        _startAnimation(carWifiLl, 900, animatorProperty);
        _startAnimation(carSaveLl, 900, animatorProperty);
        _startAnimation(carCallLl, 900, animatorProperty);

        _startAnimation(carRecordLl, 600, animatorProperty);
        _startAnimation(carCollectionLl, 600, animatorProperty);
        _startAnimation(carQueryLl, 600, animatorProperty);
    }


    /**
     * 关闭 popupWindow执行的动画
     */
    public void _rlClickAction() {
        if (ivBtn != null && rlClick != null) {

            ObjectAnimator objectAnimator = ObjectAnimator.ofFloat(ivBtn, "rotation", 180f, 0f);
            objectAnimator.setDuration(300);
            objectAnimator.start();

            _closeAnimation(carWifiLl, 400, top);
            _closeAnimation(carSaveLl, 400, top);
            _closeAnimation(carCallLl, 400, top);

            _closeAnimation(carRecordLl, 500, bottom);
            _closeAnimation(carCollectionLl, 500, bottom);
            _closeAnimation(carQueryLl, 500, bottom);

//            _close();
//            rlClick.postDelayed(new Runnable() {
//                @Override
//                public void run() {
//                    _close();
//                }
//            }, 400);

        }
    }


    /**
     * 弹起 popupWindow
     *
     * @param context context
     * @param parent  parent
     */
    public void _show(Activity context, View parent, String currentVin, View bgView) {
        _createView(context);
        if (popupWindow != null && !popupWindow.isShowing()) {
            popupWindow.showAtLocation(parent, Gravity.NO_GRAVITY, 0, 0);
            _openPopupWindowAction();
        }
        vin = currentVin;
        this.bgView = bgView;
        if (bgView != null) {
            bgView.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 关闭popupWindow
     */

    public void _close() {
        if (bgView != null) {
            bgView.setVisibility(View.GONE);
        }
        if (popupWindow != null && popupWindow.isShowing()) {
            popupWindow.dismiss();
            popupWindow = null;
        }
    }

    /**
     * @return popupWindow 是否显示了
     */
    public boolean _isShowing() {
        if (popupWindow == null) {
            return false;
        } else {
            return popupWindow.isShowing();
        }
    }


    /**
     * 弹起 popupWindow
     *
     * @param context context
     * @param parent  parent
     */
    public void top_show(Context context, View parent, List<HomeCarDataBean.ResultBean.VehinfosBean> vehinfosBeans, OnItemCheckedChange onItemCheckedChange) {
        creatTopPopuWindow(context, vehinfosBeans, onItemCheckedChange);
        if (topPopuWindow != null && !topPopuWindow.isShowing()) {
            topPopuWindow.showAtLocation(parent, Gravity.CENTER, 0, 0);
            topPopuWindow.setAnimationStyle(R.style.mypopwindow_anim_style);
            Activity activity = (Activity) context;
            backgroundAlpha(0.3f, activity);
            topPopuWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    Activity activity = (Activity) context;
                    backgroundAlpha(1f, activity);
                }
            });
        }
    }

    /**
     * 关闭topPopuWindow
     */

    public void top_close() {
        if (topPopuWindow != null && topPopuWindow.isShowing()) {
            topPopuWindow.dismiss();
            topPopuWindow = null;
        }
    }


    /* 设置添加屏幕的背景透明度
     * @param bgAlpha
     * 让popupWindow实现dialog效果
     */

    public void backgroundAlpha(float bgAlpha, Activity context) {
        WindowManager.LayoutParams lp = context.getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        context.getWindow().setAttributes(lp);
    }

    /**
     * @return topPopuWindow 是否显示了
     */
    public boolean top_isShowing() {
        if (topPopuWindow == null) {
            return false;
        } else {
            return topPopuWindow.isShowing();
        }
    }

    /**
     * 关闭 popupWindow 时的动画
     *
     * @param view     mView
     * @param duration 动画执行时长
     * @param next     平移量
     */
    private void _closeAnimation(View view, int duration, int next) {
        ObjectAnimator anim = ObjectAnimator.ofFloat(view, "translationY", 0f, next);
        anim.setDuration(duration);
        anim.start();
        anim.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                _close();
            }
        });
    }

    /**
     * 启动动画
     *
     * @param view     view
     * @param duration 执行时长
     * @param distance 执行的轨迹数组
     */
    private void _startAnimation(View view, int duration, float[] distance) {
        ObjectAnimator anim = ObjectAnimator.ofFloat(view, "translationY", distance);
        anim.setDuration(duration);
        anim.start();
    }


}
